// 股票自动提示功能
const stockSymbolInput = document.getElementById('stockSymbol');
const stockSuggestions = document.getElementById('stockSuggestions');
let searchTimeout = null;
let stockCache = null; // 缓存股票列表
let lastSearchTerm = '';

// 初始化股票建议功能
export function initStockSuggestions() {
    if (!stockSymbolInput || !stockSuggestions) return;
    
    // 监听输入事件
    stockSymbolInput.addEventListener('input', handleInput);
    
    // 监听失焦事件
    stockSymbolInput.addEventListener('blur', () => {
        // 延迟隐藏，以便点击建议项
        setTimeout(() => {
            stockSuggestions.classList.add('hidden');
        }, 200);
    });
    
    // 监听聚焦事件
    stockSymbolInput.addEventListener('focus', () => {
        if (stockSymbolInput.value.trim() && !stockSuggestions.classList.contains('hidden')) {
            stockSuggestions.classList.remove('hidden');
        }
    });
    
    // 点击建议项时的处理
    stockSuggestions.addEventListener('click', (e) => {
        const suggestionItem = e.target.closest('.suggestion-item');
        if (suggestionItem) {
            stockSymbolInput.value = suggestionItem.dataset.symbol;
            stockSuggestions.classList.add('hidden');
            // 可以在这里添加自动分析逻辑
        }
    });
    
    // 阻止事件冒泡
    stockSuggestions.addEventListener('mousedown', (e) => {
        e.preventDefault();
    });
}

// 处理输入事件
function handleInput() {
    const searchTerm = stockSymbolInput.value.trim().toLowerCase();
    
    // 如果搜索词相同，不重复查询
    if (searchTerm === lastSearchTerm) return;
    
    lastSearchTerm = searchTerm;
    
    // 清除之前的定时器
    if (searchTimeout) {
        clearTimeout(searchTimeout);
    }
    
    // 如果输入为空，隐藏建议
    if (!searchTerm) {
        stockSuggestions.classList.add('hidden');
        return;
    }
    
    // 添加防抖，延迟查询
    searchTimeout = setTimeout(() => {
        fetchStockSuggestions(searchTerm);
    }, 300);
}

// 获取股票建议
async function fetchStockSuggestions(searchTerm) {
    try {
        // 优先使用缓存的股票数据
        if (stockCache) {
            const filteredStocks = filterStocks(stockCache, searchTerm);
            displaySuggestions(filteredStocks);
            return;
        }
        
        // 从服务器获取所有股票
        const response = await fetch('/api/stocks/all');
        
        // 检查响应状态
        if (!response.ok) {
            // 即使响应状态不是200，也尝试解析JSON，因为服务器可能返回了错误详情
            try {
                const errorData = await response.json();
                console.warn('获取股票数据失败:', errorData.error || '未知错误');
            } catch (parseError) {
                console.warn('获取股票数据失败，无法解析响应');
            }
            
            // 使用本地备用数据
            useLocalFallbackData(searchTerm);
            return;
        }
        
        // 解析响应数据
        const data = await response.json();
        
        // 检查是否有错误
        if (data.error) {
            console.warn('获取股票数据失败:', data.error);
            useLocalFallbackData(searchTerm);
            return;
        }
        
        // 提取股票数据
        stockCache = Array.isArray(data.stocks) ? data.stocks : [];
        console.log(`股票数据加载成功，来源: ${data.source || 'unknown'}，共 ${stockCache.length} 条`);
        
        // 过滤股票
        const filteredStocks = filterStocks(stockCache, searchTerm);
        displaySuggestions(filteredStocks);
        
    } catch (error) {
        console.error('获取股票建议失败:', error);
        // 发生异常时使用本地备用数据
        useLocalFallbackData(searchTerm);
    }
}

// 使用本地备用数据
function useLocalFallbackData(searchTerm) {
    console.log('使用本地备用股票数据');
    
    // 本地备用股票数据
    const fallbackData = [
        {'symbol': '600519.SS', 'symbol_standardized': '600519', 'stock_name': '贵州茅台', 'industry': '白酒'},
        {'symbol': '000858.SZ', 'symbol_standardized': '000858', 'stock_name': '五粮液', 'industry': '白酒'},
        {'symbol': '002594.SZ', 'symbol_standardized': '002594', 'stock_name': '比亚迪', 'industry': '新能源汽车'},
        {'symbol': '601318.SS', 'symbol_standardized': '601318', 'stock_name': '中国平安', 'industry': '保险'},
        {'symbol': '600036.SS', 'symbol_standardized': '600036', 'stock_name': '招商银行', 'industry': '银行'},
        {'symbol': '000002.SZ', 'symbol_standardized': '000002', 'stock_name': '万科A', 'industry': '房地产'},
        {'symbol': '600000.SS', 'symbol_standardized': '600000', 'stock_name': '浦发银行', 'industry': '银行'},
        {'symbol': '000725.SZ', 'symbol_standardized': '000725', 'stock_name': '京东方A', 'industry': '电子'},
        {'symbol': '601166.SS', 'symbol_standardized': '601166', 'stock_name': '兴业银行', 'industry': '银行'},
        {'symbol': '601328.SS', 'symbol_standardized': '601328', 'stock_name': '交通银行', 'industry': '银行'},
        {'symbol': '600031.SS', 'symbol_standardized': '600031', 'stock_name': '三一重工', 'industry': '工程机械'},
        {'symbol': '601668.SS', 'symbol_standardized': '601668', 'stock_name': '中国建筑', 'industry': '建筑装饰'},
        {'symbol': '600019.SS', 'symbol_standardized': '600019', 'stock_name': '宝钢股份', 'industry': '钢铁'},
        {'symbol': '000858.SZ', 'symbol_standardized': '000858', 'stock_name': '五粮液', 'industry': '白酒'}
    ];
    
    // 设置缓存并过滤
    stockCache = fallbackData;
    const filteredStocks = filterStocks(fallbackData, searchTerm);
    displaySuggestions(filteredStocks);
}

// 过滤股票
function filterStocks(stocks, searchTerm) {
    return stocks.filter(stock => {
        const code = stock.symbol_standardized.toLowerCase();
        const name = stock.stock_name ? stock.stock_name.toLowerCase() : '';
        
        // 匹配股票代码或名称
        return code.startsWith(searchTerm) || name.includes(searchTerm);
    }).slice(0, 10); // 最多显示10条建议
}

// 显示建议
function displaySuggestions(stocks) {
    // 清空之前的建议
    stockSuggestions.innerHTML = '';
    
    if (stocks.length === 0) {
        // 显示无结果提示
        const noResult = document.createElement('div');
        noResult.className = 'px-4 py-2 text-neutral-500';
        noResult.textContent = '未找到匹配的股票';
        stockSuggestions.appendChild(noResult);
    } else {
        // 创建建议项
        stocks.forEach(stock => {
            const item = document.createElement('div');
            item.className = 'suggestion-item px-4 py-2 hover:bg-neutral-100 cursor-pointer transition-colors';
            item.dataset.symbol = stock.symbol_standardized;
            
            // 高亮匹配的部分
            const nameElement = document.createElement('div');
            nameElement.className = 'font-medium';
            nameElement.textContent = stock.stock_name;
            
            const codeElement = document.createElement('div');
            codeElement.className = 'text-sm text-neutral-500';
            codeElement.textContent = `代码: ${stock.symbol_standardized}${stock.industry ? ' | 行业: ' + stock.industry : ''}`;
            
            item.appendChild(nameElement);
            item.appendChild(codeElement);
            stockSuggestions.appendChild(item);
        });
    }
    
    // 显示建议框
    stockSuggestions.classList.remove('hidden');
}

